/** @file    Sprinkler.cpp
 *  @author  Alessandro Polo
 *  @version $Id: Sprinkler.cpp 2891 2010-08-12 01:58:59Z alex $
 *  @brief
 * File containing methods for the wosh::building::Sprinkler class.
 * The header for this class can be found in Sprinkler.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/
 
 #include <framework/building/Sprinkler.h>

 #include <core/ObjectAllocator.h>
 #include <core/List.h>
 #include <core/MethodsCommon.h>


namespace wosh {
 namespace building {

 WOSH_REGISTER(wosh::building::Sprinkler, "wosh::building::BuildingObject", _Sprinkler_VERSION, _static_Sprinkler )

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS

Sprinkler::Sprinkler()
	: BuildingObject() {
	BuildingObject::setName( "wosh.building.Sprinkler", _GET_Abs(Utilities::randomLong()) );
 }

void Sprinkler::init() {
	Log(LOG_DEBUG, " Setting default properties and permissions.." );

	Properties.set( _Sprinkler_KEY_Device, "", Permission(Permission::RW, Permission::RW, Permission::Read) );
//	Properties.set( _Sprinkler_KEY_ExternalSprinkler, false, Permission(Permission::RW, Permission::RW, Permission::Read) );
//	Properties.set( _Sprinkler_KEY_PowerWatt, false, Permission(Permission::RW, Permission::RW, Permission::Read) );

	this->state = Sprinkler::STATE_UNKNOWN;
	setState(Sprinkler::STATE_UNKNOWN, false);

	Log(LOG_DEBUG, " Registering methods.." );


	BuildingObject::init();
 }

//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT Sprinkler::setChild( const std::string& object_uri, InterfacesProvider* interfaces ) {
	WRESULT ret = BuildingObject::setChild(object_uri, interfaces);
	std::string uri = getChildByInterface(wosh::interfaces::devices::Switch::bundleType());
	Properties.update( _Sprinkler_KEY_Device, uri );
	return ret;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////// PROCESS CHILD MESSAGES

void Sprinkler::busMessageChild( const Message& childMessage ) {
	if ( childMessage.isEmpty() ) return;
	if ( !childMessage.getContent()->isFact() ) return;
	const Fact* fact = childMessage.getContent()->asFact();
	if ( fact == NULL ) return;

 }

////////////////////////////////////////////////////////////////////////////////////// PROCESS CHILD MESSAGES
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////// GENERATED EVENTS

void Sprinkler::setState( Sprinkler::SPRINKLER_STATE new_state, bool raise_event, const SecurityToken* source_token ) {
	Sprinkler::SPRINKLER_STATE old_state = this->state;
	Properties.transactionBeginWrite();
	if ( this->state != new_state ) {
		this->state = new_state;
		Properties.update( _BuildingObject_KEY_State, getStateAsString() );
	 }
	Properties.update( _BuildingObject_KEY_StateTs, Variant(Utilities::std_time(), Variant::DATETIME) );
	Properties.transactionEnd();
	if ( this->raiseAlwaysEvents || raise_event ) {
		Log(LOG_VERBOSE, ":setState(%s) Raising Event.. ", getStateAsString() );
		//BuildingObject::raiseEvent( new Room_NoiseChanged(this->stateNoise, old_state), source_token );
		BuildingObject::raiseEvent( new Fact( _BuildingObject_EVENT_StateChanged, new Variant(getStateAsString()) ), source_token );
	 }
	else
		Log(LOG_DEBUG, ":setState(%s) Not Raising Event.", getStateAsString() );
 }

//////////////////////////////////////////////////////////////////////////////////////////// GENERATED EVENTS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////// DEVICE METHODS

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
WRESULT Sprinkler::mmDoSetVolumeUp( const SecurityToken* security ) {
	Log(LOG_INFO, ":mmDoSetVolumeUp()" );
	BuildingObject::controlChild( getChildByInterface(_PlayerAudio_TYPE), new Request( _Player_METHOD_set_volume, new Variant("+") ), security );
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT Sprinkler::mmDoSetVolumeDown( const SecurityToken* security ) {
	Log(LOG_INFO, ":mmDoSetVolumeDown()" );
	BuildingObject::controlChild( getChildByInterface(_PlayerAudio_TYPE), new Request( _Player_METHOD_set_volume, new Variant("-") ), security );
	return WRET_OK;
 }
*/
////////////////////////////////////////////////////////////////////////////////////////////// DEVICE METHODS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool Sprinkler::updateHash( DataHashContext* hash_context ) const {
	if ( hash_context == NULL ) return false;
	bool ret = BuildingObject::updateHash( hash_context );
	ret = hash_context->update( this->state ) & ret;
	return ret;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

const char* SprinklerStateStr[] = {
	"UNKNOWN",	// (SPRINKLER_STATE)0
	"IDLE",		// (SPRINKLER_STATE)1
	"OPENED"	// (SPRINKLER_STATE)2
 };

Enum2StrFromArray(Sprinkler::getStateAsString, Sprinkler::SPRINKLER_STATE, STATE_IDLE, STATE_OPENED, 0, SprinklerStateStr)

Str2EnumByArray(Sprinkler::getStateFromString, Sprinkler::SPRINKLER_STATE, 0, STATE_OPENED, STATE_UNKNOWN, SprinklerStateStr)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

Sprinkler::SPRINKLER_STATE intToSprinklerStateEnum( int value ) {
	if ( value <= Sprinkler::STATE_UNKNOWN ) return Sprinkler::STATE_UNKNOWN;
	if ( value > Sprinkler::STATE_OPENED ) return Sprinkler::STATE_UNKNOWN;
	return (Sprinkler::SPRINKLER_STATE)value;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 WOSH_REGISTER(wosh::building::Sprinkler_StateChanged, "wosh::Fact", 1.0, _static_Sprinkler_StateChanged )

Sprinkler_StateChanged::Sprinkler_StateChanged( Sprinkler::SPRINKLER_STATE current_audiobox_state )
	: wosh::Fact( _BuildingObject_EVENT_StateChanged ) {
	setData( new Variant( (int)current_audiobox_state ) );
 }

Sprinkler_StateChanged::Sprinkler_StateChanged( Sprinkler::SPRINKLER_STATE current_audiobox_state, int current_volume )
	: wosh::Fact( _BuildingObject_EVENT_StateChanged ) {
	List* args = List::createFrom<Variant>( (int)current_audiobox_state, (int)current_volume );
	setData(args);
 }

Sprinkler_StateChanged::Sprinkler_StateChanged( Sprinkler::SPRINKLER_STATE current_audiobox_state, int current_volume,
												Sprinkler::SPRINKLER_STATE previous_appliance_state, int previous_volume )
	: wosh::Fact( _BuildingObject_EVENT_StateChanged ) {
	List* list = new List(4);
	list->push_back<Variant>( (int)current_audiobox_state );
	list->push_back<Variant>( (int)current_volume );
	list->push_back<Variant>( (int)previous_appliance_state );
	list->push_back<Variant>( (int)previous_volume );
	setData(list);
 }

Sprinkler::SPRINKLER_STATE Sprinkler_StateChanged::getSprinklerState() const {
	if ( !hasData() ) return Sprinkler::STATE_UNKNOWN;
	if ( content->isKindOf<Variant>() ) {
		const Variant* val = content->as<Variant>();
		if ( val == NULL ) return Sprinkler::STATE_UNKNOWN;
		return intToSprinklerStateEnum(val->toInteger((int)Sprinkler::STATE_UNKNOWN));
	 }
	if ( getData()->isKindOf<List>() ) {
		const List* list = getData()->as<List>();
		if ( list == NULL ) return Sprinkler::STATE_UNKNOWN;
		if ( list->size() < 1 ) return Sprinkler::STATE_UNKNOWN;
		if ( list->itemAt(0) == NULL ) return Sprinkler::STATE_UNKNOWN;
		const Variant* val = list->itemAt(0)->as<Variant>();
		if ( val == NULL ) return Sprinkler::STATE_UNKNOWN;
		if ( !val->isNumeric() ) return Sprinkler::STATE_UNKNOWN;
		return intToSprinklerStateEnum(val->toInteger((int)Sprinkler::STATE_UNKNOWN));
	 }
	return Sprinkler::STATE_UNKNOWN;
 }

int Sprinkler_StateChanged::getVolume() const {
	if ( !hasData() ) return 0;
	if ( getData()->isKindOf<List>() ) {
		const List* list = getData()->as<List>();
		if ( list == NULL ) return 0;
		if ( list->size() < 2 ) return 0;
		if ( list->itemAt(1) == NULL ) return 0;
		const Variant* val = list->itemAt(1)->as<Variant>();
		if ( val == NULL ) return 0;
		if ( !val->isNumeric() ) return 0;
		return val->toInteger(0);
	 }
	return 0;
 }

Sprinkler::SPRINKLER_STATE Sprinkler_StateChanged::getPreviousSprinklerState() const {
	if ( !hasData() ) return Sprinkler::STATE_UNKNOWN;
	if ( getData()->isKindOf<List>() ) {
		const List* list = getData()->as<List>();
		if ( list == NULL ) return Sprinkler::STATE_UNKNOWN;
		if ( list->size() < 3 ) return Sprinkler::STATE_UNKNOWN;
		if ( list->itemAt(2) == NULL ) return Sprinkler::STATE_UNKNOWN;
		const Variant* val = list->itemAt(2)->as<Variant>();
		if ( val == NULL ) return Sprinkler::STATE_UNKNOWN;
		if ( !val->isNumeric() ) return Sprinkler::STATE_UNKNOWN;
		return intToSprinklerStateEnum(val->toInteger((int)Sprinkler::STATE_UNKNOWN));
	 }
	return Sprinkler::STATE_UNKNOWN;
 }

int Sprinkler_StateChanged::getPreviousVolume() const {
	if ( !hasData() ) return 0;
	if ( getData()->isKindOf<List>() ) {
		const List* list = getData()->as<List>();
		if ( list == NULL ) return 0;
		if ( list->size() < 4 ) return 0;
		if ( list->itemAt(3) == NULL ) return 0;
		const Variant* val = list->itemAt(3)->as<Variant>();
		if ( val == NULL ) return 0;
		if ( !val->isNumeric() ) return 0;
		return val->toInteger(0);
	 }
	return 0;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace building
}; // namespace wosh
